<?php

namespace App\Http\Controllers\API\LifeCycle\Package;

use App\Http\Controllers\Controller;
use App\Http\Resources\PackageOrderCollection;
use App\Http\Resources\PackageOrderDetailResource;
use App\Http\Resources\PackageOrderResource;
use App\Models\CarPackageOrder;
use App\Models\CarPackageOrderAttr;
use App\Services\LifeCycle\OrderAgreementService;
use App\Services\LifeCycle\OrderService;
use App\Services\LifeCycle\PackageService;
use App\Services\LifeCycle\UsedService;
use App\Services\LifeCycle\UserCarsService;
use App\Services\LifeCycle\WechatService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{

    protected $model = CarPackageOrder::class;
    protected $collection = PackageOrderCollection::class;
    protected $resource = PackageOrderResource::class;

    /**
     * @param Request $request
     */
    public function orderList(Request $request)
    {
        $param = $request->all();
        $user = Auth::user();
        $where = [];

        //分类
        $status = $param['status'] ?? '0';

        if ($status) {
            $where['status'] = OrderService::orderStatusSwitch($status);
        }

        $keywords = $param['keywords'] ?? '';

        if ($keywords != '') {
            $where[] = ['package_title', 'like', "%{$keywords}%"];
        }

        $orm = $this->model::where('user_id', $user->id)->where($where)->orderBy('id', 'desc');

        $per_page = 10;

        $list = $orm->paginate($per_page);

        $data = new $this->collection($list);

        return $this->success($data);
    }

    public function userOrder(Request $request)
    {
        $type = $request->get('type') ?? 1;
        $user = Auth::user();

        $package_id = PackageService::packageTypeId($type);

        $order = CarPackageOrder::where('user_id', $user->id)->whereIn('package_id', $package_id)->first();

        return $this->success($order);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function sheetMetalCreate(Request $request)
    {
        $param = $request->all();
        $order = CarPackageOrder::where('package_id', PACKAGE_ID_BJQ)->where('car_number', $param['car_number'])->first();

        if (!$order) {
            $order = \App\Models\CarPackageOrder::where('package_id', PACKAGE_ID_BJQ)->where('user_phone', $param['user_phone'])->first();

            if ($order) {

                $count = CarPackageOrderAttr::where('order_id', $order->id)->count();

                if (($count+$param['coupon_attr_number']) > 5) {
                    return $this->failure("该用户已领{$count}张券，每人最多可领5张！");
                }
            }
        } else {
            $count = CarPackageOrderAttr::where('order_id', $order->id)->count();

            if (($count+$param['coupon_attr_number']) > 5) {
                return $this->failure("该用户已领{$count}张券，每人最多可领5张！");
            }
        }

        $order_create = OrderService::sheetMetalCreate($param, $order);

        if ($order_create) {
            return $this->success();
        }

        return $this->failure();
    }

    public function create(Request $request)
    {
        $order_payment = OrderService::create($request->all());

        if ($order_payment['code'] == '200') {
            if ($request->get('payment_type') == ORDER_PAYMENT_TYPE_WECHAT) {
                return $this->success(['wechat' => $order_payment['data']['data'], 'order_id' => $order_payment['data']['order_id']]);
            } else {
                return $this->success(['order_id' => $order_payment['data']['order_id']]);
            }
        } else {
            return $this->failure($order_payment['message']);
        }
    }

    public function pay(Request $request)
    {
        $order_payment = OrderService::pay($request->get('order_id'));

        if ($order_payment['code'] == 'SUCCESS') {
            return $this->success(['wechat' => $order_payment['data'], 'order_id' => $order_payment['order_id']]);
        } else {
            return $this->failure($order_payment['data']);
        }
    }

    public function detail(Request $request)
    {
        $order_id = $request->get('order_id');

        $order = new PackageOrderDetailResource(OrderService::detail($order_id));

        return $this->success([
            'order_detail' => $order
        ]);
    }

    public function agreement(Request $request)
    {
        $user = Auth::user();

        $order = CarPackageOrder::where('user_id', $user->id)->find($request->get('order_id'));
        $agreement = PackageService::agreement($order->package_id);

        if ($order->package->type == PACKAGE_TYPE_SALE) {
            if ($order->store->package_agreement) {
                $agreement->agreement = $order->store->package_agreement.'<br />'.$agreement->agreement;
            }
        } else {
            if ($order->store->after_package_agreement) {
                $agreement->agreement = $order->store->after_package_agreement.'<br />'.$agreement->agreement;
            }
        }

        return $this->success($agreement);
    }

    public function agreementSave(Request $request)
    {
        OrderAgreementService::save($request->all());

        return $this->success();
    }

    public function agreementDetail(Request $request)
    {
        $agreement = OrderAgreementService::one(['order_id' => $request->get('order_id')]);

        return $this->success($agreement);
    }

    public function packageAttr(Request $request)
    {
        $user = Auth::user();
        $order_id = $request->get('order_id');

        $package_attr = OrderService::attr($order_id, $user->id);

        return $this->success($package_attr);
    }

    public function notify()
    {
        $app = Factory::payment(config('wechat.payment.default'));

        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = CarPackageOrder::where('order_sn', $message['out_trade_no'])->first();

            if ($order->status != ORDER_STATUS_UNPAID) {
                Log::error("该订单重复回调: {$message['out_trade_no']}");

                return true;
            } else {
                if ($message['return_code'] == 'SUCCESS' && $message['result_code'] == 'SUCCESS') {
                    $order->payment_sn = $message['transaction_id'];
                    $order->payment_at = date("Y-m-d H:i:s", strtotime($message['time_end']));
                    $order->status = ORDER_STATUS_PAID;
                    $order->code_url = OrderService::orderCodeCreate($order->id);
                    $order->code_number = OrderService::orderCodeNumber($order->id);
                    $order->order_price = $order->price;

                    $order->save();

                    OrderService::orderAttrCreate($order);
                } else {
                    $remarks = "该订单回调失败：{$message['out_trade_no']} 原因：{$message['return_msg']}";
                    $order->status = ORDER_STATUS_FAILURE;
                    $order->remarks = $remarks;

                    $order->save();
                    Log::error($remarks);
                }
            }
        });

        return $response;
    }
}